﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Security;
using System.Xml.XPath;
using System.IO;
using System.Xml.Xsl;
using ObjectPersistence;
using KYO.DAL;
using Portal.API;
using System.Data;
using System.Web.UI.WebControls;
using FredCK.FCKeditorV2;
using System.Xml;

/// <summary>
/// Summary description for AddinManagerBase
/// </summary>
public class AddinManagerBase:Controller<ModuleIntall>
{


    PlaceHolder ModuleOption;
    public ModuleAssembler moduleService = new ModuleAssembler();
    public ModuleIntallAssembler moduleIntallService = new ModuleIntallAssembler();
    IAddinManager AddinManager1;

    protected override void OnInit(EventArgs e)
    {
       
        GetModel();
        ModuleOption = (PlaceHolder)FindControl("ModuleOption");
        AddinManager1 = (IAddinManager)FindControl("AddinManager1");
        CreateModuleOption();
        base.OnInit(e);
    }
     
    // called from Page's Init event handler
    private void CreateModuleOption()
    {

   



        // Load the data source
        XPathDocument ModuleOptionDoc = new XPathDocument(ModuleConfigPathOption());

        // Load the xslt to do the transformations
        XslCompiledTransform transform = new XslCompiledTransform();
        transform.Load(Server.MapPath("Options.xslt"));

        // Get the transformed result
        StringWriter sw = new StringWriter();
        transform.Transform(ModuleOptionDoc, null, sw);
        string result = sw.ToString();

        // remove the namespace attribute
        result = result.Replace("xmlns:asp=\"remove\"", "");

        // parse the control(s) and add it to the page
        Control ctrl = Page.ParseControl(result);
        ModuleOption.Controls.Add(ctrl);
    }
    protected void ProcessModuleOptionResults(string action)
    {

        //Using TranastionDecorator Start Service: Distribute Transaction
        using (TransactionDecorator transaction = new TransactionDecorator())
        {
            //


            List<string> values = new List<string>();

            //Create new Module



            // tabs is persiten list
            if (action.Equals(Action.CREATE))
            {
                Model = new ModuleIntall();
                Model.Name = AddinManager1.ModuleTitle;
                Model.ModuleObject = GetModule;
                Model.IsNew = true;
                Model.TabColl = AddinManager1.Tabs;
                moduleIntallService.MakePersistent(Model, true);
            }
            else if (action.Equals(Action.EDIT))
            {
                Model.IsNew = false;
                //for (int i = 0; i < Model.TabColl.Count; i++)
                //{
                //    if(!AddinManager1.Tabs.Contains(Model.TabColl[i]))
                //        Model.TabColl.RemoveAt(i);


                //}
                //for (int i = 0; i < AddinManager1.Tabs.Count; i++)
                //{ 
                //    if(!Model.TabColl.Contains(AddinManager1.Tabs[i]))
                //        Model.TabColl.Add(AddinManager1.Tabs[i]);
                //}

                //Error here we will check late in service Pack1
                Model.TabColl.Clear();
                moduleIntallService.MakePersistent(Model, true);
                Model.TabColl = AddinManager1.Tabs;

                moduleIntallService.MakePersistent(Model, true);
            }

            // Values of XLM options
            values.Add(Model.Name);
            values.Add((int)AddinManager1.ModulePosition + "");
            values.Add(AddinManager1.ModuleVisible.ToString());
            values.Add(AddinManager1.ModudeOdering.ToString());
            string fileName = Model.ModuleObject.ModulePath + "_" + Model.ID;
            SaveXMLConfig(fileName, values);

            transaction.Complete();
        }

    }




      protected void LoadConfigToControl()
      {

          string fileName = Model.ModuleObject.ModulePath + "_" + Model.ID;
          DataSet ds = this.ReadConfig(fileName);

          DataTable moduleTable = ds.Tables["Module"];
       
          //Create new Module

          AddinManager1.ModuleTitle =   Model.Name;
   
          //ModuleIntallModel.TabColl.Add(new Tab(1, "Home", 0));

          AddinManager1.Tabs = Model.TabColl;// tabs is persiten list

          DataRow row = moduleTable.Rows[0];
          AddinManager1.ModulePosition = (Position)(int.Parse(row["position"].ToString()));
          AddinManager1.ModuleVisible = Boolean.Parse(row["visible"].ToString());
          AddinManager1.ModudeOdering = int.Parse(row["odering"].ToString());



          // Load the data source
          XPathDocument ModuleOptionDoc = new XPathDocument(ModuleConfigPathOption());
          // create an iterator for each question
          XPathNodeIterator itr =
           ModuleOptionDoc.CreateNavigator().Select("//param");
          // string builder for ModuleOption body

          // foreach question
          while (itr.MoveNext())
          {
              // get the control name
              string controlName = itr.Current.GetAttribute("name", "");
               
             
              string value = row[controlName].ToString();

              object ctrl = FindControl(controlName);
              // append the correct filled out information
              if (ctrl is TextBox)
              {
                  //Decode HTML
                 // ((TextBox)ctrl).Text = HttpUtility.HtmlDecode(value);
                  ((TextBox)ctrl).Text = value;
              }
              if (ctrl is FCKeditor)
              {
                  ((FCKeditor)ctrl).Value = HttpUtility.HtmlDecode(value);
              }
              if (ctrl is CheckBox)
              {
                  // sb.Append(((TextBox)ctrl).Text);

                  ((CheckBox)ctrl).Checked = Boolean.Parse(value);
              }


              if (ctrl is RadioButtonList)
              {
                 
                      // sb.Append(((RadioButtonList)ctrl).SelectedItem.Value);

                      ((RadioButtonList)ctrl).SelectedValue = value;

                  
              }
              //   sb.Append(Environment.NewLine);
          }

      }

      private void SaveXMLConfig(string fileName,List<string> values)
      {

          DataSet ds = new DataSet("ModuleSetting");

          DataTable moduleTable = new DataTable();
          moduleTable.TableName = "Module";

      
          moduleTable.Columns.Add(new DataColumn("name"));
          moduleTable.Columns.Add(new DataColumn("position"));
          moduleTable.Columns.Add(new DataColumn("visible"));
          moduleTable.Columns.Add(new DataColumn("odering"));

          


          // Load the data source
          XPathDocument ModuleOptionDoc = new XPathDocument(ModuleConfigPathOption());
          // create an iterator for each question
          XPathNodeIterator itr =
           ModuleOptionDoc.CreateNavigator().Select("//param");
          // string builder for ModuleOption body

          // foreach question
          while (itr.MoveNext())
          {
              // get the control name
              string controlName = itr.Current.GetAttribute("name", "");

              moduleTable.Columns.Add(new DataColumn(controlName));


              object ctrl = FindControl(controlName);
              // append the correct filled out information
              if (ctrl is TextBox)
              {
                  // sb.Append(((TextBox)ctrl).Text);
                  //values.Add(HttpUtility.HtmlEncode(((TextBox)ctrl).Text));
                  values.Add(((TextBox)ctrl).Text);
              }
              if (ctrl is FCKeditor)
              {
                  // sb.Append(((TextBox)ctrl).Text);
                  //values.Add(HttpUtility.HtmlEncode(((TextBox)ctrl).Text));
                  values.Add( HttpUtility.HtmlEncode(((FCKeditor)ctrl).Value));
              }
              if (ctrl is CheckBox)
              {
                  // sb.Append(((TextBox)ctrl).Text);
                  values.Add(((CheckBox)ctrl).Checked.ToString());
              }


              if (ctrl is RadioButtonList)
              {
                  // the selected item might be null
                  if (((RadioButtonList)ctrl).SelectedItem != null)
                  {
                      // sb.Append(((RadioButtonList)ctrl).SelectedItem.Value);
                      values.Add(((RadioButtonList)ctrl).SelectedItem.Value);

                  }
              }
              //   sb.Append(Environment.NewLine);
          }








          moduleTable.Rows.Add(values.ToArray());
          ds.Tables.Add(moduleTable);



          //moduleIntallService.MakePersistent(ModuleIntallModel, true);
         //  string fileName = GetModule.ModulePath + "_" + ModuleIntallModel.ID;
          WriteConfig(ds, fileName);



      }

     

    public void WriteConfig(DataSet ds, string FileName)
    {
        // if (null == ds)
        //  throw new ArgumentException(Language.GetText("exception_NullReferenceParameter"), "ds");
        try
        {
            ds.WriteXml(ModuleConfigFile(FileName));
        }
        catch (SecurityException e)
        {
            // Do not throw exceptions

        }
    }
    public DataSet ReadConfig(string fileName)
    {
        DataSet ds = null;
        try
        {
            if (System.IO.File.Exists(ModuleConfigFile(fileName)))
            {
                ds = new DataSet();
               
                ds.ReadXml(ModuleConfigFile(fileName));
            }
        }
        catch (SecurityException e)
        {
            // Do not throw exceptions
            Trace.Warn("Module", Language.GetText("ErrorLoadingModulesConfigDataset"), e);
            return null;
        }

        

        return ds;
    }


    public string ModuleConfigFile(string fileName)
    {



        return Server.MapPath("~/App_Data/Configures/Options/") + fileName + ".xml";


    }
    public string ModuleConfigPathOption()
    {
        //string config = "~/Modules/"+ 
        return Server.MapPath("~/Modules/" + GetModule.ModulePath + "/Option.xml");
    }

    public Module GetModule
    {
        get
        {
            // Module module ;
            //We check later
             object o = Request.QueryString["moduleId"];
             if (o != null)
             {
                 string moduleId = Request.QueryString["moduleId"].ToString();
                 return moduleService.ReadSingleByKey(int.Parse(moduleId));

             }
             else
             {
                 if (Model == null)
                 {
                     Model = GetModel();
                 }
                 
                 return Model.ModuleObject;
             }
        }

    }
    //private ModuleIntall moduleIntall = new ModuleIntall();

    //public ModuleIntall ModuleIntallModel
    //{
    //    get { return moduleIntall; }
    //    set { moduleIntall = value; }
    //}
    protected KYO.DAL.ModuleIntall GetModel()
    {
        
        object o = Request.QueryString["id"];
        if (o != null)
        {
            string id = o.ToString();
            Model = moduleIntallService.ReadSingleByKey(int.Parse(id));
        }
        else Model = new ModuleIntall();
        return Model;

    }
}
